package com.lilicould.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;

/**
 * MyBatis 工具类
 * 封装创建SqlSession的方法
 * @author lilicould
 */
public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            // 加载 mybatis-config.xml 配置
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("MyBatis 初始化失败");
        }
    }

    // 获取 SqlSession（手动提交事务时用 openSession(true) 自动提交）
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession(true);
    }
}